import time
from urllib.parse import unquote

import requests
import threading
import pymysql.cursors


def download_file_zone(url, spos, fpos, fp):
    try:
        header = {}
        header["Range"] = "bytes=%d-%d" % (spos, fpos)
        res = requests.get(url, headers=header)
        fp.seek(spos)
        fp.write(res.content)
        print("downloaded bytes=%d-%d" % (spos, fpos), end=' ')
    except Exception as e:
        print("downloadFile error: %s" % e)


def download_file(url):
    res = requests.head(url)
    url = res.headers.get("Location")
    res = requests.head(url)
    url = res.headers.get("Location")
    res = requests.head(url)
    filename = res.headers.get("Content-Disposition").split('=')[1]
    # 获取文件名称
    filename = unquote(filename).replace("+", " ").replace("\"", "")
    filename = "H:\\KuGou\\%s" % filename
    size = int(res.headers.get("Content-Length"))
    print("total size: %d" % size)
    n = 30
    spos = []
    fpos = []
    persize = int(size / n)
    intsize = persize * n  # 整除部分
    for i in range(0, intsize, persize):
        spos.append(i)
        fpos.append(i + persize - 1)
    if intsize < size:  # size 不一定 n 等分，将不能等分余下的部分添加到最后一个 sub 里
        fpos[n - 1] = size
    fp = open(filename, "wb")
    fp.close()
    fp = open(filename, "rb+")
    tmp = []
    start_time = time.time()  # 计时起始点，为了计算平均速度
    for i in range(0, n):
        t = threading.Thread(target=download_file_zone, args=(url, spos[i], fpos[i], fp))
        t.setDaemon(True)  # 主进程结束时，线程也随之结束
        t.start()
        tmp.append(t)
    for i in tmp:
        i.join()  # 等待线程结束
    fp.close()
    finish_time = time.time()  # 计时终点，为了计算平均速度
    speed = float(size) / (1000.0 * (finish_time - start_time))
    print("spend time: %0.2f s" % float(finish_time - start_time))
    print("finished... average speed: %0.2f KB/s" % speed)


if __name__ == '__main__':
    connection = pymysql.connect(host="127.0.0.1", user="root", password="root", db="common", charset="utf8mb4")
    cursor = connection.cursor()
    try:
        # 创建sql语句
        sql = "SELECT `id`,`flag`,`download_url`,`file_name` FROM `music_51ape` WHERE `flag`=2"
        # 执行sql语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            print("开始下载：%s" % row[3])
            download_file(row[2])
            # 创建sql语句
            sql = "update `music_51ape` set `flag`=3 where `id`=%s"
            # 执行sql语句
            cursor.execute(sql, (row[0]))
            # 提交
            connection.commit()
    finally:
        connection.close()
